package redis

import (
	"cart_srv/cart"
	"strconv"
)

// GetGoodsStock 获取商品数量
func GetGoodsStock(goodsId int) int64 {
	key := "goods_stock:goods_id_" + strconv.Itoa(goodsId)
	return Rdb.LLen(key).Val()
}

// CartAdd 添加购物车
func CartAdd(userId, goodsId int, cart map[string]interface{}) error {

	key := "cart_user_id_" + strconv.Itoa(userId) + ":goods_id_" + strconv.Itoa(goodsId)
	err := Rdb.HMSet(key, cart).Err()
	if err != nil {
		return err
	}
	return nil
}

// 购物车列表
func CartList(userId int) (cartList []*cart.CartList, err error) {
	key := "cart_user_id_" + strconv.Itoa(userId) + ":*"
	result, _ := Rdb.Keys(key).Result()
	for _, v := range result {
		h, _ := Rdb.HGetAll(v).Result()
		goodsId, _ := strconv.Atoi(h["goodsId"])
		quantity, _ := strconv.Atoi(h["quantity"])
		goodsName, _ := h["goodsName"]
		goodsPrice, _ := strconv.ParseFloat(h["goodsPrice"], 64)
		status, _ := strconv.Atoi(h["status"])
		cartList = append(cartList, &cart.CartList{
			UserId:     int32(userId),
			GoodsId:    int32(goodsId),
			Quantity:   int32(quantity),
			GoodsName:  goodsName,
			GoodsPrice: float32(goodsPrice),
			Status:     int32(status),
		})
	}
	return cartList, nil

}

// ClearCart 清空购物车
func ClearCart(userId int) error {
	key := "cart_user_id_" + strconv.Itoa(userId) + ":*"
	val := Rdb.Keys(key).Val()
	for _, v := range val {
		Rdb.Del(v)
	}
	return nil
}

func DelCart(userId, goodsId int) error {
	key := "cart_user_id_" + strconv.Itoa(userId) + ":goods_id_" + strconv.Itoa(goodsId)
	val := Rdb.Keys(key).Val()
	Rdb.Del(val...)
	return nil
}

// GetCartUserIdAndGoodsIdIsExists 购物车中商品是否存在
func GetCartUserIdAndGoodsIdIsExists(userId, goodsId int) bool {
	key := "cart_user_id_" + strconv.Itoa(userId) + ":goods_id_" + strconv.Itoa(goodsId)
	//fmt.Println(key)

	result, err := Rdb.Exists(key).Result()
	if err != nil {
		return false
	}
	return result == 1
}

// 更新
func UpdateCartNum(userId, goodsId, quantity int) error {

	key := "cart_user_id_" + strconv.Itoa(userId) + ":goods_id_" + strconv.Itoa(goodsId)

	Rdb.HIncrBy(key, "quantity", int64(quantity))
	return nil
}

// 购物车总价总数量计算
func SumCart(userId int) (cartList []*cart.CartList, count int, amount float64, err error) {
	count = 0
	amount = 0.00
	key := "cart_user_id_" + strconv.Itoa(userId) + ":*"
	result, _ := Rdb.Keys(key).Result()
	for _, v := range result {
		h, _ := Rdb.HGetAll(v).Result()
		quantity, _ := strconv.Atoi(h["quantity"])
		goodsPrice, _ := strconv.ParseFloat(h["goodsPrice"], 64)
		cartList = append(cartList, &cart.CartList{
			Quantity:   int32(quantity),
			GoodsPrice: float32(goodsPrice),
		})
		count += quantity
		amount += goodsPrice * float64(quantity)
	}
	return cartList, count, amount, nil
}
